//
//  BindPhoneNumberView.swift
//  Kosspot
//
//  Created by 李鑫 on 2025/8/25.
//

import SwiftUI

struct BindPhoneNumberView: View {
    @EnvironmentObject var appState:AppState
    @State private var scene = "bindMobile"
    @StateObject var viewModel = LoginViewModel()
    var accessToken: String =  ""
    var openid: String =  ""
    var unionid: String = ""
    
    @State private var showToast = false

    
    var body: some View {
        VStack {
            ZStack {
                Image("6528")
                    .resizable()
                    .frame(height: 210)
                
                Image("Kosspot")
                    .resizable()
                    .frame(width: 116,height: 52)
                    .padding(.top,30)
                VStack {
                    Image("6711")
                        .resizable()
                        .frame(width: 143,height: 26)
                        .padding(.top,65)
                        .padding(.leading,-22)
                }
            }
            
            ZStack(alignment: .leading) {
                RoundedRectangle(cornerRadius: 8)
                    .fill(Color(hex: "#F5F6FA"))
                    .frame(height: 44)
                HStack {
                    Menu {
                        ForEach(viewModel.countryCodes, id: \.self) { item in
                            Button {
                                viewModel.selectedCode = item
                            } label: {
                                Text(item)
                            }
                        }
                    } label: {
                        HStack(alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/, content: {
                            Text(viewModel.selectedCode)
                                .foregroundColor(.black)
                            Spacer().frame(width: 2)
                            Image("sanjiao")
                        })
                        .lineSpacing(0)
                    }
                    .frame(height: 44)
                    .padding(.leading, 18)
                    Spacer().frame(width: 8)
                    Capsule()
                        .frame(width: 1.3, height: 18)
                        .foregroundColor(Color (hex: "#B5B5B5"))

                    Spacer().frame(width: 8)
                    ZStack(alignment: .leading) {
                        if viewModel.username.isEmpty {
                            Text("请输入手机号码")
                                .font(.system(size: 16))
                                .foregroundColor(Color (hex: "#B5B5B5"))
                        }
                        TextField("", text: $viewModel.username)
                            .font(.system(size: 16))
                            .keyboardType(.phonePad)
                            .frame(height: 44)
                            .padding(.trailing, 18)
                            .foregroundColor(Color.black)
                            .autocapitalization(UITextAutocapitalizationType/*@START_MENU_TOKEN@*/.none/*@END_MENU_TOKEN@*/)
                    }
                }
            }
            .padding(.horizontal, 24)
            
            Spacer().frame(height: 16)
            
            
            HStack (alignment: .center, content:{
                ZStack(alignment:.leading) {
                    RoundedRectangle(cornerRadius: 8)
                        .fill(Color(hex: "#F5F6FA"))
                        .frame(height: 44)
                    if viewModel.code.isEmpty {
                        Text("请输入验证码")
                            .font(.system(size: 16))
                            .foregroundColor(Color (hex: "#B5B5B5"))
                            .padding(.leading, 18)
                    }
                    SecureField("", text: $viewModel.code)
                        .font(.system(size: 16))
                        .frame(height: 44)
                        .padding(.horizontal, 18)
                        .foregroundColor(Color.black)
                        .autocapitalization(UITextAutocapitalizationType.none)
                    
                }
                CountdownButton(mobile: $viewModel.username) {
                    viewModel.sendSMCcode(mobile: viewModel.username, scene: scene)
                }
            })
            .frame(height: 44)
            .background(Color(hex: "#F5F6FA"))
            .cornerRadius(8.0)
            .padding(.horizontal, 24)
            .padding(.top, 16)
          
            HStack {
                Spacer()
                Button(action: {
                    if viewModel.username.isEmpty {
                        viewModel.error = "请输入手机号码"
                        return
                    }
                    if viewModel.code.isEmpty {
                        viewModel.error = "请输入验证码"
                        return
                    }
                    viewModel.error = nil
                    viewModel.bindMobile(accessToken:accessToken,oauthType: "wechat", openid: openid, unionid: unionid, mobile: viewModel.username, code: viewModel.code)

                }, label: {
                    HStack(alignment: .center, spacing: 0) {
                        Text("绑定")
                            .font(.system(size: 16))
                            .foregroundColor(Color(hex: "#242424"))
                    }
                    .frame(maxWidth: .infinity, alignment: .center)
                })
                .padding()
                .alert(isPresented: $viewModel.isLoginSuccess, content: {
                    Alert(title: Text("提示"), message: Text("绑定成功!"), dismissButton: .default(Text("确认"), action: {
                        viewModel.isLoginSuccess = false
                        viewModel.error = nil
                        appState.navigateTo(.tabbar)
                    })
                    )
                })
                Spacer()
            }
            .gradientBackground(colors: [Color(hex: "#00F3AF"),Color(hex: "#00E9DA")])
            .cornerRadius(8.0)
            .padding([.trailing,.leading],24)
            .padding(.top, 16)
            Spacer()
        }
        .navigationBarHidden(false)
        .background(Color(hex: "#0A0A0A"))
        .edgesIgnoringSafeArea(.all)
        .customNavigationBar(title: "绑定手机", backButtonAction: {
            appState.navigateBack()
        }, backgroundColor: UIColor(.clear))
        .dismissingKeyboard()
        .toast(isPresented: $showToast) {
            ShowMessageView(message: viewModel.error)
        }
        .onChange(of: viewModel.error) {
            newValue in
            if let errorMessage = newValue, !errorMessage.isEmpty {
                showToast = true
                DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                    showToast = false
                    viewModel.error = nil
                }
            }
        }
    }
}

